// 默认声明一个函数记录list显示的数据---删除状态
var initdata = function (that) {
  var list = that.data.cartData
  for (var i = 0; i < list.length; i++) {
    list[i].shows = ""
  }
  that.setData({
    list: list
  })
}
//购物车页面
var app = getApp();

Page({
  data: {
    startX: 0, //开始坐标
    startY: 0,
    cartData: {}, //购物车数据
    cartIds: [], //选中ids
    checkboxAll: false, //全选按钮
    total: 0.00, //总价
    goSettlement: false, //去结算按钮
    cartId: '',
    cartNum: '',
    isLoad: false,
    cartNums: 0,
    baseurl: 'https://wukongweixiu.cn/',
    delBtnWidth: 185,
    
  },

  onLoad:function (){
    this.initEleWidth();
  },
  // 开始滑动事件
  touchstart: function (e) {
    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置 
        startX: e.touches[0].clientX
      });
    }
  },
  touchmove: function (e) {
    var that = this;
    initdata(that)
    if (e.touches.length == 1) {
      //手指移动时水平方向位置 
      var moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值 
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      // var txtStyle = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，文本层位置不变 
        // txtStyle = "left:0px";
      } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离 
        // txtStyle = "left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度 
          // txtStyle = "left:-" + delBtnWidth + "px";
        }
      }
    }
  },
  // 滑动中事件
  touchE: function (e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置 
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离 
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮 
      var txtStyle = "";
      txtStyle = disX > delBtnWidth / 2 ? delBtnWidth: 0;
      //获取手指触摸的是哪一项 
      var index = e.currentTarget.dataset.index;
      var list = this.data.cartData;
      if (txtStyle > 0){
        list[index].isTouchMove = true;
      }else{
        list[index].isTouchMove = false;
      }
      //更新列表的状态 
      this.setData({
        cartData: list
      });
    } else {
      console.log("2");
    }
  },
  //获取元素自适应后的实际宽度 
  getEleWidth: function (w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2); //以宽度750px设计稿做宽度的自适应 
      // console.log(scale); 
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error 
    }
  },
  initEleWidth: function () {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },
  //点击删除按钮事件 
  delItem: function (e) {
    var that = this;
    // 打印出当前选中的index
    // console.log(e.currentTarget.dataset.index);
    // 获取到列表数据
    var list = that.data.cartData;
    // 删除
    list.splice(e.currentTarget.dataset.index, 1);
    // 重新渲染
    that.setData({
      list: cartData
    })
    initdata(that)
  },
  //是否全选
  isAllCheckbox: function () {
    var page = this;
    var cartData = page.data.cartData;
    var goSettlement = false;
    var flag = true;
    for (var key in cartData) {
      if (cartData[key].is_select == false) {
        flag = false;
      }
      if (cartData[key].is_select == true) {
        goSettlement = true;
      }
    }
    if (cartData.length <= 0) {
      flag = false;
    }
    this.setData({
      checkboxAll: flag,
      goSettlement: goSettlement
    });
  },
  //选择操作
  checkbox: function (e) {
    var page = this;
    var id = e.currentTarget.dataset.id; 
    var cartData = page.data.cartData;
    for (var key in cartData) {
      if (key == id) {
        var carid = cartData[key].id; 
        if (cartData[key].is_select == true) {
          cartData[key].is_select = false;
        } else {
          cartData[key].is_select = true;
        }
      }
    }
    page.setData({
      cartData: cartData
    });
    page.setNumsData();
    page.isAllCheckbox();
    page.tosetIs_select(carid);
  },
  //全选操作
  checkboxAll: function (e) {
    if (this.data.checkboxAll == true) {
      this.setData({
        checkboxAll: false
      });
      this.setAllCheckbox(false);
    } else {
      this.setData({
        checkboxAll: true
      });
      this.setAllCheckbox(true);
    }

  },
  //全选设置
  setAllCheckbox: function (e) {
    // console.log(e)
    var page = this;
    var cartData = page.data.cartData;
    if (e) {
      //全选
      for (var key in cartData) {
        cartData[key].is_select = true;
      }
    } else {
      //全不选
      for (var key in cartData) {
        cartData[key].is_select = false;
      }
    }
    page.setData({
      cartData: cartData
    });
    page.setNumsData();
    page.isAllCheckbox();
    page.salcedall(e);
  },

  //设置刷新数据
  setNumsData: function () {
    var page = this;
    var cartData = page.data.cartData;
    var cartIds = [];
    var total = 0;
    for (var key in cartData) {
      if (cartData[key].is_select) {
        cartIds.push(cartData[key].id);
        total = total + (cartData[key].goodsmun * cartData[key].price)
      }
    }
    page.setData({
      cartIds: cartIds,
      cartData: cartData,
      total: total
    });
 
  },
  salcedall: function (value) {
    var page = this;
    wx.request({
      url: 'https://wukongweixiu.cn/index/Defaults/salcedall',
      data: {
        unionid: getApp().globalData.userid,
        value: value
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'GET',
      success: function (res) { }
    })
  },
  tosetIs_select: function (id){
    var page = this;
    wx.request({
      url: 'https://wukongweixiu.cn/index/Defaults/updatasalced',
      data: {
        id: id,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'GET',
      success: function (res) {}
    })
  },
  //更新数据库
  tosetGoodscar: function (id, mun, op) {
    var page = this;
    wx.request({
      url: 'https://wukongweixiu.cn/index/Defaults/updata',
      data: {
        id: id,
        mun: mun,
        op: op,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'GET',
      success: function (res) {
        page.setNumsData();
        page.isAllCheckbox();
      }
    })
  },

  //数量减一
  bindMinus: function (e) {
    var page = this;
    var id = e.currentTarget.dataset.id;
    var num = 1;
    var cartData = page.data.cartData;
  
    for (var key in cartData) {
      if (cartData[key].id == id) {
        if (cartData[key].goodsmun > 1) {
          cartData[key].goodsmun--;
          num = cartData[key].goodsmun;
        } else {
          return false
        }
      }
    }
    page.setData({
      cartData: cartData,
      cartId: id,
      cartNum: num
    });
    page.tosetGoodscar(id, num,'goodsmun');
  },
  //数量加一
  bindPlus: function (e) {
    var page = this;
    var id = e.currentTarget.dataset.id;
    var num = 1;
    var cartData = page.data.cartData;
    for (var key in cartData) {
      if (cartData[key].id == id) {
        if (cartData[key].goodsmun < 10000) {
          cartData[key].goodsmun++;
          num = cartData[key].goodsmun;
        
        } else {
          return false;
        }
      }
    }
    page.setData({
      cartData: cartData,
      cartId: id,
      cartNum: num
    });
    page.tosetGoodscar(id, num, 'goodsmun');
  },


  //输入框数量改变
  bindManual: function (e) {
    var page = this;
    var id = e.currentTarget.dataset.id;
    var num = 1;
    var cartData = page.data.cartData;
    for (var key in cartData) {
      if (cartData[key].id == id) {
        if (e.detail.value < 1){
          e.detail.value = 1;
        }
        if (e.detail.value >=10000) {
          e.detail.value = 10000;
        }
        cartData[key].goodsmun = e.detail.value;
        num = cartData[key].goodsmun;
      }
    }
    page.setCartNum(id, num);
  },

  //设置购物车数量
  setCartNum: function (id, nums) {
    var page = this;
    var data = {
      id: id,
      nums: nums
    }
    //提交到数据库
    page.tosetGoodscar(id, nums, 'goodsmun');
  },

  //删除事件
  del: function (e) {
    var page = this;
    //移除渲染
    page.data.cartData.splice(e.currentTarget.dataset.index, 1);
    page.setData({
      cartData: page.data.cartData
    });
    //移除数据库
    wx.request({
      url: 'https://wukongweixiu.cn/index/Defaults/delcar',
      data: {
        car_id: e.currentTarget.dataset.cartid,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'GET',
      success: function (res) {
        page.setNumsData();
        page.isAllCheckbox();
      }
    })
  },


  //去结算
  settlement: function (e) {
    var page = this;
    if (page.data.goSettlement) {
      var cartData = page.data.cartData;
      var newData = '';
      for (var key in cartData) {
        if (cartData[key].is_select == true) {
          newData += ',' + cartData[key].id;
        }
      }
      if (newData.substr(0, 1) == ',') {
        newData = newData.substr(1);
      }
      // console.log(newData);
      if (newData.length > 0) {
        wx.navigateTo({
          url: '../firmOrder/firmOrder?data=' + JSON.stringify(newData),
        });
      } else {
        //没有选择不跳转
      }
    }
  },
  //查看商品详情
  goodsDetail: function (e) {
    wx.navigateTo({
      url: '../detail/detail?id=' + e.currentTarget.dataset.id
    });
  },
  //页面加载
  onShow: function () {
    var that = this
    wx.request({
      //这是我自己的java服务器的接口，将login（）获得的code发送的服务器换取session_key
      url: 'https://wukongweixiu.cn/index/Defaults/getcar',
      data: {
        user_id:getApp().globalData.userid,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'GET',
      success: function (res) {
        console.log(res.data.data.cardata)
        that.setData({
          cartData: res.data.data.data.data,
          checkboxAll: res.data.data.is_selectall,
          goSettlement: res.data.data.cardata
        })
        that.setNumsData();
      }
    })
  }
});